package com.keter.framework.persist.util;

import com.keter.framework.core.exception.ValidateException;
import com.keter.framework.persist.base.BaseModel;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ValidateUtil {
    /**
     * Logger for this class
     */
    private static final Logger logger = LoggerFactory.getLogger(ValidateUtil.class);

    private BaseModel m;

    //类加载时就进行实例化
    private static ValidateUtil m_instance = new ValidateUtil();

    //构造方式私有化，保证外界无法直接实例化
    private ValidateUtil(){
        
    }
    
    public ValidateUtil(BaseModel model){
        this.m = model;
    }

    /**
     * 校验对象是否为空：为空时直接抛出校验异常
     * @param obj
     * @param msg
     */
    public static void notNull(Object obj, String msg) {
        if(obj==null){
            throw new ValidateException(msg);
        }
    }

    public  ValidateUtil notEmpty(String attr){
        try {
            Validate.notEmpty(m.getStr(attr).trim());
        } catch (Exception e) {
            logger.error("inValidate attr: [{}] - {}",attr,e.getMessage());
            throw new ValidateException("校验失败:字段["+attr+"]内容不能为空!");
        }
        return this;
    }
    
    public ValidateUtil min(String attr, int minLen){
        length(attr,minLen,Integer.MAX_VALUE);
        return this;
    }
    
    public ValidateUtil max(String attr, int maxLen){
        length(attr,0, maxLen);
        return this;
    }

    public ValidateUtil minMax(String attr, int minLen,int maxLen){
        length(attr,minLen,maxLen);
        return this;
    }

    public ValidateUtil length(String attr, int minLen, int maxLen){
        String value = m.getStr(attr);
        if (value == null || value.length() < minLen || value.length() > maxLen){
            logger.error("inValidate attr: [{}]",attr);
            throw new ValidateException("校验失败:字段内容长度不符合要求");
        }
        return this;
    }
}
